/*
 * Copyright (c) 2018-2999 广州市蓝海创新科技有限公司 All rights reserved.
 *
 * https://www.mall4j.com/
 *
 * 未经允许，不可做商业用途！
 *
 * 版权所有，侵权必究！
 */

package com.yami.shop.service.impl;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yami.shop.bean.app.dto.UserDeductionFundDto;
import com.yami.shop.bean.dto.UserVipLevelDto;
import com.yami.shop.bean.enums.UserFundDetailEnum;
import com.yami.shop.bean.model.User;
import com.yami.shop.bean.model.UserFundDetail;
import com.yami.shop.bean.param.UserRegisterParam;
import com.yami.shop.common.exception.YamiShopBindException;
import com.yami.shop.common.util.RedisUtil;
import com.yami.shop.dao.UserMapper;
import com.yami.shop.service.UserFundDetailService;
import com.yami.shop.service.UserService;
import jodd.util.StringUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * @author lgh on 2018/09/11.
 */
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private UserFundDetailService userFundDetailService;


    @Override
    @Cacheable(cacheNames = "user", key = "#userId")
    public User getUserByUserId(String userId) {
        return userMapper.selectById(userId);
    }

    /**
     * 看看有没有校验验证码成功的标识
     * @param userRegisterParam
     * @param checkRegisterSmsFlag
     */
    @Override
    public void validate(UserRegisterParam userRegisterParam, String checkRegisterSmsFlag) {
        if (StrUtil.isBlank(userRegisterParam.getCheckRegisterSmsFlag())) {
            // 验证码已过期，请重新发送验证码校验
            throw new YamiShopBindException("验证码已过期，请重新发送验证码校验");
        } else {
            String checkRegisterSmsFlagMobile = RedisUtil.get(checkRegisterSmsFlag);
            if (!Objects.equals(checkRegisterSmsFlagMobile, userRegisterParam.getMobile())) {
                // 验证码已过期，请重新发送验证码校验
                throw new YamiShopBindException("验证码已过期，请重新发送验证码校验");
            }
        }
    }

    @Override
    public List<User> getAllHigherLevelUser(String userId) {
        List<User> list=new ArrayList<>();
        User byId = this.getById(userId);
        list.add(byId);
        while (byId != null){
            userId = byId.getHigherLevelUid();
            byId = this.getById(userId);

            if (byId == null){
                break;
            }
            list.add(byId);
        }
        return list;
    }

    @Override
    public List<UserVipLevelDto> getHigherLevelVip(String userId) {
        List<UserVipLevelDto> list=new ArrayList<>();
        User byId = this.getById(userId);
        UserVipLevelDto userVipLevelDto = new UserVipLevelDto();
        userVipLevelDto.setId(byId.getUserId());
        userVipLevelDto.setVipLevel(byId.getVipLevel());
        list.add(userVipLevelDto);
        while (byId != null){
            userId = byId.getHigherLevelUid();
            byId = this.getById(userId);

            if (byId == null){
                break;
            }else{
                List<Integer> collect = list.stream().map(d -> d.getVipLevel()).collect(Collectors.toList());
                if(!collect.contains(byId.getVipLevel())){
                    UserVipLevelDto userVipLevelDto1 = new UserVipLevelDto();
                    userVipLevelDto1.setId(byId.getUserId());
                    userVipLevelDto1.setVipLevel(byId.getVipLevel());
                    list.add(userVipLevelDto1);
                }
                collect = list.stream().map(d -> d.getVipLevel()).collect(Collectors.toList());
                if(collect.contains(3)){
                    //已经找到svip,不需要在继续向上找
                    break;
                }
            }
        }
        return list;
    }

    @Override
    public List<User> getLowerLevel(String uid, ArrayList<User> objects) {
        List<User> list = this.lambdaQuery().select(User::getUserId,User::getHigherLevelUid,User::getNickName,User::getVipLevel,User::getPic)
                .eq(User::getHigherLevelUid, uid).list();
        for(User user:list){
            getLowerLevel(user.getUserId(),objects);
            objects.add(user);
        }
        return objects;
    }

    @Override
    public List<User> getLowerLevelBySharedUid(String uid, ArrayList<User> objects) {
        List<User> list = this.lambdaQuery().select(User::getUserId,User::getSharedUid,User::getNickName,User::getVipLevel,User::getPic)
                .eq(User::getSharedUid, uid).list();
        for(User user:list){
            getLowerLevel(user.getUserId(),objects);
            objects.add(user);
        }
        return objects;
    }

    @Override
    public List<UserDeductionFundDto> getUserAllDeductionFund(String userId) {
        List<UserDeductionFundDto> list=new ArrayList<>();

        //distribution_bonus字段可用户下单抵扣
        User byId = this.getById(userId);
        if(byId == null){
            return list;
        }
        if(byId.getDistributionBonus()!= null && byId.getDistributionBonus().compareTo(BigDecimal.ZERO) > 0){
            UserDeductionFundDto dto=new UserDeductionFundDto();
            dto.setUserId(byId.getUserId());
            dto.setFundMoney(byId.getDistributionBonus());
            dto.setFundName("分销奖金");
            dto.setFundField("distribution_bonus");
            dto.setDeductionMoney(BigDecimal.ZERO);
            list.add(dto);
        }
        //...继续追加其他抵扣项

        return list;
    }

    @Override
    public void userDeductionFundDeduct(List<UserDeductionFundDto> userDeductionFundDtos,String orderNumber) {
        for(UserDeductionFundDto dto:userDeductionFundDtos){
            if(StringUtil.equals(dto.getFundField(),"distribution_bonus")){
                User byId = this.getById(dto.getUserId());
                if(byId == null){
                    continue;
                }
                BigDecimal distributionBonus = byId.getDistributionBonus();
                if(distributionBonus == null){
                    distributionBonus = BigDecimal.ZERO;
                }

                BigDecimal subtract = distributionBonus.subtract(dto.getDeductionMoney());
                User user = new User();
                user.setUserId(byId.getUserId());
                user.setDistributionBonus(subtract);
                this.updateById(user);

                UserFundDetail detail=new UserFundDetail();
                detail.setUserType("tz_user");
                detail.setUid(byId.getUserId());
                detail.setCategory(UserFundDetailEnum.DISTRIBUTION_BONUS.getValue());
                detail.setType(UserFundDetailEnum.TYPE_10.getValue());
                detail.setPm(Integer.valueOf(UserFundDetailEnum.PM_0.getValue()));
                detail.setMoney(dto.getDeductionMoney());
                detail.setResidueMoney(subtract);
                detail.setTitle("下单抵扣");
                detail.setDetails("下单抵扣:"+dto.getDeductionMoney() +", 剩余:"+subtract);
                detail.setOrderNumber(orderNumber);
                detail.setDelFlag(0);

                //detail.setCreateBy(userId);
                detail.setCreateTime(new Date());
                userFundDetailService.save(detail);
            }
        }
    }

    @Override
    public void userDeductionFundReturn(List<UserDeductionFundDto> userDeductionFundDtos, String orderNumber) {
        for(UserDeductionFundDto dto:userDeductionFundDtos){
            if(StringUtil.equals(dto.getFundField(),"distribution_bonus")){
                User byId = this.getById(dto.getUserId());
                if(byId == null){
                    continue;
                }
                BigDecimal distributionBonus = byId.getDistributionBonus();
                if(distributionBonus == null){
                    distributionBonus = BigDecimal.ZERO;
                }

                BigDecimal subtract = distributionBonus.add(dto.getDeductionMoney());
                User user = new User();
                user.setUserId(byId.getUserId());
                user.setDistributionBonus(subtract);
                this.updateById(user);

                UserFundDetail detail=new UserFundDetail();
                detail.setUserType("tz_user");
                detail.setUid(byId.getUserId());
                detail.setCategory(UserFundDetailEnum.DISTRIBUTION_BONUS.getValue());
                detail.setType(UserFundDetailEnum.TYPE_11.getValue());
                detail.setPm(Integer.valueOf(UserFundDetailEnum.PM_1.getValue()));
                detail.setMoney(dto.getDeductionMoney());
                detail.setResidueMoney(subtract);
                detail.setTitle("抵扣金额退回");
                detail.setDetails("抵扣金额退回:"+dto.getDeductionMoney() +", 剩余:"+subtract);
                detail.setOrderNumber(orderNumber);
                detail.setDelFlag(0);

                //detail.setCreateBy(userId);
                detail.setCreateTime(new Date());
                userFundDetailService.save(detail);
            }
        }
    }

    public static void main(String[] args) {
        List list=new ArrayList();
        list.add(null);
        System.out.println(list.contains(null));
    }
}
